// var rootContext = "http://localhost:8090/mentor-server/";
var rootContext = "http://39.106.10.2:8090/mentor-server/";

function ajaxServerUrlG(subUrl) {
	var ret = rootContext + "generator/";
	if (StringUtils.isNotEmpty(subUrl)) {
		ret = ret + subUrl;
	}
	var token = getQueryString("token");
	if (StringUtils.isNotEmpty(token)) {
		ret = ret + "?token=" + token;
	}
    return ret;
}

function ajaxServerUrlS(subUrl) {
	var ret = rootContext + "sys/";
	if (StringUtils.isNotEmpty(subUrl)) {
		ret = ret + subUrl;
	}
	var token = getQueryString("token");
	if (StringUtils.isNotEmpty(token)) {
		ret = ret + "?token=" + token;
	}
    return ret;
}

function getUploadFileUrl() {
	return ajaxServerUrlG("lss/upload");
}

function getDownFileUrl(subUrl) {
	return ajaxServerUrlG("lss/download/" + subUrl);
}

$(function () {
    var headerH = $(".header").height();
    orient();
    //获取今天时间
    var getdate = new Date(new Date().getTime()).Format("yyyy-MM-dd");
    if (/iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase())) {
        $("input[id=money]").attr("type", "number");
    } else {
        $("input[id=money]").attr("type", "tel")
    }
    
	if (/iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase())) {
	    window.alert = function(name){
	        var iframe = document.createElement("IFRAME");
	        iframe.style.display="none";
	        iframe.setAttribute("src", 'data:text/plain,');
	        document.documentElement.appendChild(iframe);
	        window.frames[0].window.alert(name);
	        iframe.parentNode.removeChild(iframe);
    	};
	}
});

function goprompt() {
    $("#goprompt").click(function () {
        var type = $(this).attr("data");
        if (window.location.href.indexOf("?") >= 0) {
            location.href = "prompt.html" + locationSearch() + "&type=" + type;
        } else {
            location.href = "prompt.html?type=" + type;
        }
    })
}

//竖屏
$(window).bind('orientationchange', function (e) {
    orient();
});

//校验密码是否合规
function checkPassword(type, password, certificateNo, mobilePhone) {
    hideLoading();
    //showLoading();
    $.ajax({
        type: 'post',
        timeout: 60000,
        url: ajaxUrl() + "checkPassword",
        data: {
            merchantId: merchantId,
            channel: channel,
            version: version,
            uuid: uuid,
            Mac: Mac,
            user_type: user_type,
            platform: platform,
            phone_type: phone_type,
            appChannel: appChannel,
            token: token,
            type: type,
            certificateNo: certificateNo,           //证件号码
            password: password,                     //交易密码
            mobilePhone: mobilePhone        //手机号
        },
        dataType: 'json',
        success: function (data) {
            hideLoading();
            var a = data.data;
            if (data.respCode == "0000") {
                $.cookie("tag", 1);
            } else {
                setErrorMsg(data.respCode, data.respMsg);
            }
        },
        error: function (data) {
            hideLoading();
            if (data.statusText == "timeout") {
                errorShowAlert("请求超时");
            } else if (data.status == "200") {
                setErrorMsg(data.respCode, data.respMsg);
            } else {
                errorShowAlert("请求失败，请稍后再试。");
            }
        }
    })
}

//接口返回码
function setErrorMsg(errorcode, errormsg, callback) {
    hideLoading();
    hideAlert();
    if (errormsg == "" || errormsg == null || errormsg == "undefined" || errormsg == undefined) {
        if (errorcode == 1000) {
            errorShowAlert("请求参数不合法！");
        }
    } else {
        if (errormsg == "未登录") {

        } else if (errorcode == "DS1036" || errorcode == "1036") {
            $.cookie("loginOut", 1);
            errorShowAlert("登录超时，请重新登录", goLogin);
        } else if (errorcode == "-2032" || errorcode == "-4064") {
            errorShowAlert("用户未登录，请登录", function () {
                location.href = locationReferrer();
            });
        } else if (errorcode == "9527") {
            errorConfirmShowAlert(errormsg, goQuestion);
        } else {
            errorShowAlert(errormsg);
        }

    }
    $('#showAlert .sure').on('click', callback);
}

//地址参数
function locationSearch() {
    var search = window.location.search;
    return search;
}

//日期格式化
Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//获取日期
function GetDateStr(AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;//获取当前月份的日期
    var d = dd.getDate();
    return y + "-" + m + "-" + d;
}

function dateCompare(a, b) {
    var arr = a.split("-");
    var starttime = new Date(arr[0], arr[1], arr[2]);
    var starttimes = starttime.getTime();

    var arrs = b.split("-");
    var lktime = new Date(arrs[0], arrs[1], arrs[2]);
    var lktimes = lktime.getTime();

    if (starttimes > lktimes) {
        return false;
    }
    else
        return true;
}


//字符串截取
var getArgs = function () { //作用是获取当前网页的查询条件
    var args = new Object(); //声明一个空对象
    var query = window.location.search.substring(1); // 取查询字符串，如从http://www.snowpeak.org/testjs.htm?a1=v1&a2=&a3=v3#anchor 中截出 a1=v1&a2=&a3=v3。
    var pairs = query.split("&"); // 以 & 符分开成数组
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('='); // 查找 "name=value" 对
        if (pos == -1) continue; // 若不成对，则跳出循环继续下一对
        var argname = pairs[i].substring(0, pos); // 取参数名
        var value = pairs[i].substring(pos + 1); // 取参数值
        value = decodeURIComponent(value); // 若需要，则解码
        args[argname] = value; // 存成对象的一个属性
    }
    return args; // 返回此对象
};

//清除cookie
function clearCookie() {
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (var i = keys.length; i--;)
            document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
    }
}


//js判断屏幕横竖屏：
function orient() {
    //alert('gete');
    // if (window.orientation == 0 || window.orientation == 180) {
    //     $("body").attr("class", "portrait");
    //     orientation = 'portrait';
    //     return false;
    // }
    // else if (window.orientation == 90 || window.orientation == -90) {
    //     $("body").attr("class", "landscape");
    //     orientation = 'landscape';
    //
    //     return false;
    // }
}

var args = new getArgs();
var merchantId = args.merchantId;
var version = args.version;
var uuid = args.uuid; //机器ID
var Mac = args.Mac; //Mac地址
var user_type = args.user_type;
var phone_type = args.phone_type;
var appChannel = args.appChannel;

var token = args.token;

var isFromApp = args.isFromApp;
var fontS = $("html").css("font-size").replace("px", "") - 0;
var headH = 0;
if (isFromApp == "true") {
    $(".header").hide();
    $("body").css("padding-top", "0");
    headH = fontS * (3.6 * 100) / 100;
}

//跳转登录
function goLogin(url) {
    if (isFromApp == "true") {
        location.href = "icbccs://u_login" + locationSearch(); //客户端返回登录
    } else {
        if (url) {
            location.href = url;  //web返回登录
        } else {
            location.href = "login.html" + locationSearch();  //web返回登录
        }
    }
}

function locationReferrer() {
    var refererUrl = document.referrer;
    var host = refererUrl.split("?")[0];
    var parse = refererUrl.split("?")[1];
    var url = "";
    if (parse) {
        var parseJson = parse.substring(0).split("&");
        url = "?";
        for (var i = 0; i < parseJson.length; i++) {
            var pos = parseJson[i].indexOf('='); // 查找 "name=value" 对
            if (pos == -1) continue; // 若不成对，则跳出循环继续下一对
            var argname = parseJson[i].substring(0, pos); // 取参数名
            var value = parseJson[i].substring(pos + 1); // 取参数值
            value = decodeURIComponent(value); // 若需要，则解码
            if (argname != "token" && argname != "cusNo") {
                if (i == parseJson.length - 1) {
                    url += argname + "=" + value
                } else {
                    url += argname + "=" + value + "&";
                }
            }
        }
    }
    return host + url
}

var pswTest = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,8}$/; //6到8位数字字母组合
var commaTest = /^.*[\,，].*$/; //是否有逗号
var moneyTest = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/; //是否是数字

//小数点后2位不能继续输入
function inputVal(inputId) {
    $("#" + inputId).bind('input propertychange', function () {
        var val = Math.floor($("#" + inputId).val() * 100) / 100;
        var valArr = $("#" + inputId).val().split(".");
        if (!!val) {
            if (valArr.length > 1) {
                if (valArr[1].length >= 2) {
                    $("#" + inputId).val(val);
                }
            }
        }
        if ($("#" + inputId).val().length > 13) {
            $("#" + inputId).val($("#" + inputId).val().substring(0, 13));
        }
    });
}

/**
 * 字符串数字转为数字，方便求和
 * @author Lichia Ma
 * @param {*} str
 */
function transStringToNumber(str) {
    if (str && str != 'undefined' && str != 'null') return parseFloat(str);
    return 0;
}

/**
 * 数字转化为逗号分隔的形式
 * @author lichia
 * @param {number|string} num
 */
function formatNumber(num) {
    if (!/^(\+|-)?(\d+)(\.\d+)?$/.test(num)) {
        return num;
    }
    var a = RegExp.$1, b = RegExp.$2, c = RegExp.$3;
    var re = new RegExp("(\\d)(\\d{3})(,|$)");
    while (re.test(b)) b = b.replace(re, "$1,$2$3");
    return a + "" + b + "" + c;
}

/*阻止ios拖拽到底部还能继续拖拽*/

var ScrollFix = function (elem) {
    // Variables to track inputs
    var startY, startTopScroll;

    elem = elem || document.querySelector(elem);

    // If there is no element, then do nothing
    if (!elem)
        return;

    // Handle the start of interactions
    elem.addEventListener('touchstart', function (event) {
        startY = event.touches[0].pageY;
        startTopScroll = elem.scrollTop;

        if (startTopScroll <= 0)
            elem.scrollTop = 1;

        if (startTopScroll + elem.offsetHeight >= elem.scrollHeight)
            elem.scrollTop = elem.scrollHeight - elem.offsetHeight - 1;
    }, false);
};

/*判断设备调用ScrollFix*/

var sUserAgent = navigator.userAgent.toLowerCase();
if (sUserAgent.match(/iphone os/i) == "iphone os") {
    $('.wrapper').addClass('wrapper2');
    ScrollFix($('.wrapper2')[0]);
}

/*阻止用户双击使屏幕上滑*/
var agent = navigator.userAgent.toLowerCase();        //检测是否是ios
var iLastTouch = null;                                //缓存上一次tap的时间
if (agent.indexOf('iphone') >= 0 || agent.indexOf('ipad') >= 0) {
    document.body.addEventListener('touchend', function (event) {
        var iNow = new Date()
            .getTime();
        iLastTouch = iLastTouch || iNow + 1 /** 第一次时将iLastTouch设为当前时间+1 */;
        var delta = iNow - iLastTouch;
        if (delta < 500 && delta > 0) {
            event.preventDefault();
            return false;
        }
        iLastTouch = iNow;
    }, false);
}


//每三位加逗号并保留小数
function fmoney(s, n) {
    var pm = "";
    if (s < 0) {
        pm = "-";
    }
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((Math.abs(s) + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
    var t = "";
    for (i = 0; i < l.length; i++) {
        if (l != '-') {
            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
        }
    }
    return pm + t.split("").reverse().join("") + "." + r;
}

//文字滚动
function sc() {
    var $scrollobj = document.getElementById('scrollobj');

    function scroll(self) {
        /*往左*/
        var tmp = (self.scrollLeft)++;
        //当滚动条到达右边顶端时
        if (self.scrollLeft == tmp) {
            self.innerHTML += "&nbsp;&nbsp;&nbsp;&nbsp;" + self.innerHTML;
        }
        //当滚动条滚动了初始内容的宽度时滚动条回到最左端
        if (self.scrollLeft >= self.firstChild.offsetWidth) {
            self.scrollLeft = 0;
        }
    }

    if ($scrollobj.scrollWidth > $scrollobj.offsetWidth) {   // 判断是否需要滚动
        var timer = setInterval(function () {
            scroll($scrollobj);
        }, 30);
    }
}


//交互物理返回
function openback(data) {
    if (/iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase())) {
        if (data == 0) {
            closeBack();
        } else {
            openBack();
        }
    } else {
        if (data == 0) {
            window.js_invoke.closeBack();
        } else {
            window.js_invoke.openBack();
        }

    }
}


//错误提示框
function errorShowAlert(str, callback, flag) {
    var title = "提示";
    if (flag == 1) {
        title = "风险提示";
    } else if (flag == 5) {
        title = "温馨提示";
    }
    hideAlert();
    var showBox;
    var showBox_h = '';
    showBox_h += '<div class="showBox">';
    showBox_h += '<div id="showAlert" class="showAlert">';
    showBox_h += '<div class="showContent">';
    showBox_h += '<div class="alert_title">' + title + '</div>';
    showBox_h += '<div class="alert_info"><span class="prompt">' + str + '</span></div>';
    showBox_h += '</div>';
    showBox_h += '<div class="subButton"><a class="sure">确定</a></div>';
    showBox_h += '</div>';
    showBox_h += '</div>';
    showBox = $(showBox_h);
    $("body").append(showBox);
    var scrollHeight = $(window).height(); //屏幕尺寸高度
    $(".showBox").css("height", scrollHeight);
    var bookHeight = $(".showAlert").height();
    $("#showAlert").css("margin-top", -(bookHeight + headH) / 2);
    $(".subButton .sure").click(function () {
        hideAlert();//购买基金接口
        if (flag == 5) {
            location.href = "icbccs://changeLongTittle" + locationSearch();
        }
        if (callback) {
            callback();
        }
    });
}

//确认提示框
function confirmShowAlert(flag, str, callback, data1, data2, data3, data4, data5, data6, data7) {
    var title = "风险提示";
    if (flag == 1) {
        title = "风险承诺函";
    } else if (flag == 2) {
        title = "评测提示";
    } else if (flag == 3) {
        title = "提示";
    } else if (flag == 5) {
        title = "温馨提示";
    }
    hideAlert();
    var showBox;
    var showBox_h = '';
    showBox_h += '<div class="showBox">';
    showBox_h += '<div id="showAlert" class="showAlert">';
    showBox_h += '<div class="showContent">';
    showBox_h += '<div class="alert_title">' + title + '</div>';
    showBox_h += '<div class="alert_info"><span class="prompt">' + str + '</span></div>';
    showBox_h += '</div>';
    if (flag == 2 || flag == 5) {
        showBox_h += '<div class="subButton"><a class="cancle">否</a><a class="confirm">确定</a></div>';
    } else {
        showBox_h += '<div class="subButton"><a class="cancle">取消</a><a class="confirm">确定</a></div>';
    }
    showBox_h += '</div>';
    showBox_h += '</div>';
    showBox = $(showBox_h);
    $("body").append(showBox);
    var scrollHeight = $(window).height(); //屏幕尺寸高度
    $(".showBox").css("height", scrollHeight);
    var bookHeight = $(".showAlert").height();
    $("#showAlert").css("margin-top", -(bookHeight + headH) / 2);
    $(".subButton .confirm").click(function () {
        if (callback) {
            callback(data1, data2, data3, data4, data5, data6, data7);
        }
    });
    $(".subButton .cancle").click(function () {
        if (flag == 2) {
            history.go(-1);
        } else {
            if (flag == 5) {
                location.href = "icbccs://changeLongTittle" + locationSearch();
            }
            hideAlert();
        }
    });
}

//新版联系客服提示框
function serviceShowAlertNew(str, callback) {
    hideAlert();
    var showBox;
    var showBox_h = '';

    showBox_h += '<div class="showBox">';
    showBox_h += '<div id="showAlert" class="showAlert">';
    showBox_h += '<div class="showContent">';
    showBox_h += '<div class="alert_title">温馨提示<img src="./images/close.png"></div>';
    showBox_h += '<div class="alert_info"><span class="prompt">' + str + '</span></div>';
    showBox_h += '</div>';
    showBox_h += '<div class="subButton"><a href="tel:4008119999" class="tel_service">客服电话</a><a class="confirm">在线客服</a></div>';
    showBox_h += '</div>';
    showBox_h += '</div>';
    showBox = $(showBox_h);
    $("body").append(showBox);
    var scrollHeight = $(window).height(); //屏幕尺寸高度
    $(".showBox").css("height", scrollHeight);
    var bookHeight = $(".showAlert").height();
    $("#showAlert").css("margin-top", -(bookHeight + headH) / 2);
    $(".subButton .confirm").click(function () {
        if (callback) {
            callback();
        }
    });
    $(".showAlert .alert_title img").click(function () {
        hideAlert();
    });
}

//输入密码
function enterCode(flag, money, callback, data1) {
    var unit = "份";
    var title = "";
    var fundCode = $.cookie("fundCode");
    hideAlert();
    var showmoney = "";
    if (flag == 0) {
        title = "购买";
        showmoney = fmoney(money) + "元";
    } else if (flag == 1) {
        title = "赎回";
        showmoney = fmoney(money) + "份";
    } else if (flag == 2) {
        title = "转换";
        showmoney = fmoney(money) + "份";
    } else if (flag == 3) {
        title = "定投";
        showmoney = fmoney(money) + "元";
    }
    var showBox;
    var showBox_h = '';
    showBox_h += '<div class="showBox">';
    showBox_h += '<div id="showAlert" class="showAlert">';
    showBox_h += '<div class="showContent">';
    showBox_h += '<div class="alert_title">' + title + '<span style="color: #c7000a"> ' + showmoney + '</span></div>';
    showBox_h += '<div class="alert_info enterCode"><input type="password" id="password" class="password" placeholder="请输入您的交易密码" maxlength="8"></div>';
    showBox_h += '</div>';
    showBox_h += '<div class="subButton"><a class="cancle">取消</a><a class="confirm">确定</a></div>';
    showBox_h += '</div>';
    showBox_h += '</div>';
    showBox = $(showBox_h);
    $("body").append(showBox);
    var scrollHeight = $(window).height();
    $(".showBox").css("height", scrollHeight);
    var bookHeight = $(".showAlert").height();
    $("#showAlert").css("margin-top", -(bookHeight + headH) / 2);
    $(".subButton .confirm").click(function () {
        if (callback) {
            callback(data1);
        }
    });
    $(".subButton .cancle").click(function () {
        hideAlert();
    });
    $("#password").bind('input propertychange', function () {
        var regExp = /^[A-Za-z0-9]+$/;
        var val = $("#password").val();
        if (!regExp.test(val.substring(val.length - 1, val.length))) {
            $("#password").val($("#password").val().substring(0, val.length - 1));
        }
    });
//输入密码框得焦后placeholder消失
    $('#password').on('click', function () {
        $(this).removeAttr("placeholder");
    });

}

//去掉提示框
function hideAlert() {
    if ($(".showBox")) {
        $(".showBox").remove();
    }
}

function showLoading() {
    var loading = $('<div class="loadinggif"></div>');
    var loadingBox = $('<div class="showLoading"></div>');
    loadingBox.append(loading);
    $("body").append(loadingBox);
    var scrollHeight = $(window).height();
    $(".showLoading").css("height", scrollHeight);
    var bookHeight = $(".loadinggif").height();
    $(".loadinggif").css("top", (scrollHeight - bookHeight - headH) / 2);
}

function hideLoading() {
    hideAlert();
    if ($(".showLoading")) {
        $(".showLoading").remove();
    }
}

//用获取到的公钥进行rsa加密
function RSA(data) {
    var key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjZkZ7Boy5eIPisR9aLc0RvUhbTVAOcgP2qb540P/d5F6zhNO34mQd/meoOC9qGijelczl3r4jfwDT1kV7Zql2ewl3+ek0rQiN3UjCZLwdpCMkcheu6TJlQC+uU8MsspfKrKyTv7xRN1OUuKlQKKbBE6f7xzNwg5a5UcI+3T3+GgHvfE4l79LrRG0PdrmQ8YJJ5jN6joE2FGsq6p6FJ/3SQE+tKYaPinwRZoRSvZDE8mGAToR/YaUmjqMLkLX3ifgMM9q4QqGmX5SsQ6Bo6nLsEKJ1UEIWr8IjO/tT8T2MLEEfWAqGTrO6AhNuhfp5goPLmDaCn8YFQH7YbeXSo496QIDAQAB';
    if (data == "") {
        var _data = "";
    } else {
        var encrypt = new JSEncrypt();
        encrypt.setPublicKey(key);
        var _data = encrypt.encrypt(data);
    }
    return _data
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
